package cn.com.guage.flink.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 
 * @author yangdechao
 *   流数据处理
 *
 */
public class SocketStreamWordCount {
    public static void main(String[] args) throws Exception{
    	
    	//linux里面执行nc -lk  9527
        //创建流处理执行环境
		StreamExecutionEnvironment streamEnv = StreamExecutionEnvironment.getExecutionEnvironment();
		streamEnv.setParallelism(4);
        //从socket文本流读取数据
        DataStream<String> inputDataStream = streamEnv.socketTextStream("192.168.0.128",9528);
        System.out.println("并行度为："+inputDataStream.getParallelism());

        //基于数据流进行转换计算
        DataStream<Tuple2<String, Integer>> resultSum = inputDataStream.flatMap(new MyFlatMapper()).keyBy(0).sum(1);
      
        System.out.println("并行度为："+resultSum.getParallelism());

        resultSum.print();
        streamEnv.execute();
    }
    
    //自定义类，实现FlatMapFunction接口
    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String,Integer>>{

        /**
		 * 
		 */
		private static final long serialVersionUID = -6332218868988874763L;

		public void flatMap(String s, Collector<Tuple2<String, Integer>> collector){
            //按空格分词
            String[] words = s.split(" ");
            //遍历所有word 加工成二元组
            for(String word:words){
                collector.collect(new Tuple2<String,Integer>(word,1));
            }
        }
    }
}
